function addLilAttachment(btn) {
	var table = $(btn).closest('table');
	var rowClone = $('tbody:last > tr:first', table).clone();
	
	clearInvoiceAnalyticsRow(rowClone);
	
	var i = 0;
	while ($('#LilBlogsAttachment' + i + 'Filename').size() > 0) i++;
	renumberInvoiceAnalyticsRow(rowClone, 0, i);
	
	$('tbody:last', table).append(rowClone);
	
	return false;
}

function removeLilAttachment(btn, id) {
	var row = $(btn).closest('tr');
	var tBody = $(row).closest('tbody');
	
	if (id) {
		var del_list = $('<input/>')
			.attr({
				name: 'data[Post][attachments_to_delete][]',
				type: 'hidden'
			})
			.val(id);
		$(del_list).insertAfter('#PostId');
		$(row).remove();
	} else {
		if ($('tr', tBody).size() > 1) {
			$(row).remove(); // we have to remove row so we know how many rows are actually visible
		} else {
			clearInvoiceAnalyticsRow(row);
		}
	}
	
	return false;
}

function clearInvoiceAnalyticsRow(row) {
	$('.lil-attachment-filename', row).val('');
	$('.lil-attachment-title', row).val('');
	
	$('.error-message', row).remove();
	$('.error', row).removeClass('error');
	$('.form-error', row).removeClass('form-error');
}

function renumberInvoiceAnalyticsRow(row, from, to) {
	$('#LilBlogsAttachment' + from + 'Filename', row).attr('name', 'data[LilBlogsAttachment][' + to + '][filename]').attr('id', 'LilBlogsAttachment' + to + 'Filename');
	$('#LilBlogsAttachment' + from + 'Title', row).attr('name', 'data[LilBlogsAttachment][' + to + '][tilename]').attr('id', 'LilBlogsAttachment' + to + 'Title');
	$('#LilBlogsAttachment' + from + 'Model', row).attr('name', 'data[LilBlogsAttachment][' + to + '][model]').attr('id', 'LilBlogsAttachment' + to + 'Model');
	$('#LilBlogsAttachment' + from + 'ForeignId', row).attr('name', 'data[LilBlogsAttachment][' + to + '][foreign_id]').attr('id', 'LilBlogsAttachment' + to + 'ForeignId');
}